package com.ujoku.service.impl;

import com.labillusion.core.database.base.mybatis.dao.BaseDao;
import com.labillusion.core.database.base.mybatis.service.base.impl.BaseServiceImpl;
import com.labillusion.core.platform.exception.ResourceNotFoundException;
import com.ujoku.dao.CartItemDao;
import com.ujoku.domain.Cart;
import com.ujoku.domain.CartItem;
import com.ujoku.service.CartItemService;
import com.ujoku.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 14-10-19.
 */
@Service
public class CartItemServiceImpl extends BaseServiceImpl<CartItem> implements CartItemService<CartItem> {

    @Autowired
    private CartItemDao dao;

    @Override
    protected BaseDao<CartItem> getBaseDao() {
        return dao;
    }

    @Autowired
    private CartService cartService;

    @Override
    public List<CartItem> getCartIemByCartId(String cartId){
        Map<String,Object> map = new HashMap<>();
        map.put("cartId", cartId);

        return this.selectList(map);
    }
    @Override
    public Cart deleteById(Cart cart, String itemId){
        CartItem cartItem = getCartItem(itemId, cart);

        this.deleteById(itemId);
        cart.getCartItemList().remove(cartItem);
        if(cart.getCartItemList().size() == 0){
            cartService.deleteById(cart.getId());
            return null;
        }

        return cart;
    }

    @Override
    public CartItem getCartItem(String cartItemId, Cart cart) {
        CartItem cartItem = cart.getCartItemList().stream().filter(i -> i.getId().equalsIgnoreCase(cartItemId)).findFirst().orElse(null);
        if(cartItem == null)
            throw new ResourceNotFoundException("can not found cart item");
        return cartItem;
    }
}
